//
//  ViewController.swift
//  Reflection
//
//  Created by dayu on 15/6/16.
//  Copyright (c) 2015年 dayu. All rights reserved.
//

import UIKit

class Animal {
    var age: Int;
    init(age: Int) {
        self.age = age;
    }
}

class Person: Animal {
    var name: String;
    var sex: Bool = true;
    var pet: Pet?;
    
    init(name: String, age: Int) {
        self.name = name;
        super.init(age: age);
    }
}

class Student: Person {
    var stuNo: String;
    var school: String = "光明学校";
    
    init(stuNo: String, name: String, age: Int) {
        self.stuNo = stuNo;
        super.init(name: name, age: age);
    }
}

class PrimaryStudent: Student {
    var teacher: String;
    var weight: Double {
        return Double(50*2);
    }
    
    lazy var height: Double = {
        return 20;
    }()
    init(teacher:String, stuNo: String, name: String, age: Int) {
        self.teacher = teacher;
        super.init(stuNo: stuNo, name: name, age: age);
    }
    
    convenience init(teacherName: String) {
        self.init(teacher:teacherName, stuNo: "110010", name: "XiaoFang", age: 10);
    }
    
}

class Pet {
    var typeName: String;
    init(name: String) {
        self.typeName = name;
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let xiaoMing: Person = PrimaryStudent(teacherName: "WangHong");
        xiaoMing.pet = Pet(name: "Cat");
        let r = reflect(xiaoMing);
        println("类型：\(r.value)");
        println("类型：\(r.valueType)");
        println((xiaoMing as! PrimaryStudent).height);
        travelClassProperty(r);
        //利用发射可以获取类的存储属性和懒加载属性，不包含计算属性。如果有父类，反射返回的第一个属性名为super，否则，返回第一个属性的名称。
        println("属性数量：\(r.count)");
        
    }
    
    func travelClassProperty(mirror:MirrorType) {
        for idx in 0...mirror.count-1 {
            if mirror[0].0 == "super" && idx == 0{
                let mir = mirror[0].1;
                travelClassProperty(mir);
            }else {
                println("属性名：\(mirror[idx].0), 值：\(mirror[idx].1.summary)");
            }
        }
        return;
    }
}

